package com.fjwt.gz.service.activity.coupon.send;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.constants.ApiCodeEnum;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.utils.WxUtil;
import com.fjwt.gz.coupon.SendCouponBo;
import com.fjwt.gz.coupon.lkls.LklspayCouponSendService;
import com.fjwt.gz.db.base.BaseAgentApp;
import com.fjwt.gz.db.bo.CouponResultBo;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.interfaces.ISendCouponService;
import com.fjwt.gz.service.impl.*;
import com.fjwt.gz.service.mapper.FansMapper;
import com.fjwt.gz.service.mapper.SysConfigMapper;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class LklspaySendCouponService implements ISendCouponService {

    @Value("${isFormal.code}")
    private boolean isFormalCode;

    private static final Logger lklsPayLogger = LoggerFactory.getLogger("lklsPay");

    @Autowired
    private FansPayService fansPayService;
    @Autowired
    private FansMapper fansMapper;
    @Autowired
    private LklspayCouponSendService lklspayCouponSendService;

    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private ActivityAppService activityAppService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private AgentAppService agentAppService;
    @Autowired
    private ActivityAwardService activityAwardService;

    @Override
    public CouponResultBo couponSend(PayAuthEntity authEntity, Long fansId, @NonNull String payConfig, Long couponId) {
        String logPrefix = "【拉卡拉支付通道发券】";

        lklsPayLogger.info("拉卡拉发券，支付通道方出资信息：{}，fansId：{}，,卡券详情：{}",
                JSON.toJSONString(authEntity), fansId, payConfig);

        // 获取openId
        String openId = getOpenId(authEntity, fansId, logPrefix, couponId);
        SendCouponBo sendCouponBo = new SendCouponBo();

        LambdaQueryWrapper<SysConfig> sysgw = SysConfig.gw();
        sysgw.eq(SysConfig::getConfigKey, "lklspay");
        SysConfig sysConfig = sysConfigMapper.selectOne(sysgw);

        sendCouponBo.setOpenId(openId);
        sendCouponBo.setStockId(payConfig);
        sendCouponBo.setAuthConfig(JSONObject.parseObject(sysConfig.getConfigVal()));
        JSONObject jsonObject = lklspayCouponSendService.couponSend(sendCouponBo);

        CouponResultBo couponResultBo = new CouponResultBo();
        couponResultBo.setCouponThirdId(jsonObject.getString("thridCouponId"));// 微信支付宝券id
        couponResultBo.setCouponId(jsonObject.getString("tradeNo"));// 通道方内部券id(tradeNo：平台订单号)
        lklsPayLogger.info("{},发券成功返回信息：{}", logPrefix, JSONUtil.toJsonStr(couponResultBo));

        return couponResultBo;
    }

    /**
     * 获取openId
     *
     * @param authEntity
     * @param fansId
     * @param logPrefix
     * @return
     */
    public String getOpenId(PayAuthEntity authEntity, Long fansId, String logPrefix, Long couponId) {
        String openId = "";
        if (0 == authEntity.getIsCommSubject()) {
            LambdaQueryWrapper<FansPayEntity> gw = FansPayEntity.gw();
            gw.eq(FansPayEntity::getIfCode, authEntity.getIfCode());
            gw.eq(FansPayEntity::getFansId, fansId);
            FansPayEntity fansOpen = fansPayService.getOne(gw);
            lklsPayLogger.info("{}同主体查询返回信息：{}", logPrefix, JSONUtil.toJsonStr(fansOpen));
            if (Objects.isNull(fansOpen) || Objects.isNull(authEntity)) {
                ActivityAwardEntity activityAwardEntity = activityAwardService.lambdaQuery().eq(ActivityAwardEntity::getAwardId, couponId)
                        .eq(ActivityAwardEntity::getAwardType, 0).one();
                ActivityAppEntity activityAppEntity = activityAppService.lambdaQuery().eq(ActivityAppEntity::getActivityId, activityAwardEntity.getActivityId()).eq(ActivityAppEntity::getType, 1).one();
//                        AgentAppVO agentAppVO = agentAppService.selectOfficial(activityAppEntity.getAppId());
                ActivityEntity activityEntity = activityService.getById(activityAwardEntity.getActivityId());
                // 查询app秘钥
                BaseAgentApp agentApp = agentAppService.getAgentApp(activityAppEntity.getAppId());
                // 生成小程序码
                String qrCode = WxUtil.getUnlimitedQRCode(activityAppEntity.getActivityId(), activityAppEntity.getAppId(), agentApp.getAppSecret(), activityEntity.getEndTime().getTime() - System.currentTimeMillis(), isFormalCode);
                throw new BizException(ApiCodeEnum.LITE_USER_SUBJECT_OFFICIAL_ERROR, qrCode);
            }
            lklsPayLogger.info("用户信息fansId:{},用户信息：{}", fansId, JSON.toJSONString(fansOpen));
            openId = fansOpen.getOpenId();
        } else {
            FansEntity fansEntity = fansMapper.selectById(fansId);
            lklsPayLogger.info("{}异主体查询返回信息：{}", logPrefix, JSONUtil.toJsonStr(fansEntity));
            if (Objects.isNull(fansEntity) || Objects.isNull(authEntity)) {
                throw new BizException("发券参数缺失！");
            }
            lklsPayLogger.info("用户信息fansId:{},用户信息：{}", fansId, JSON.toJSONString(fansEntity));
            openId = fansEntity.getPayOpenId();
        }
        return openId;
    }

}
